package com.hhit.yb.compose_demo.viewModel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn

class TaskViewModel(app: Application): AndroidViewModel(app) {

    private val list = mutableListOf(
        Task(1L, "Task1", true),
        Task(2L, "Task2", false),
        Task(3L, "Task3", false),
        Task(4L, "Task4", false),
        Task(5L, "Task5", false),
        Task(6L, "Task6", false),
        Task(7L, "Task7", true),
        Task(8L, "Task8", false),
        Task(9L, "Task9", false),
        Task(10L, "Task10", false),
        Task(11L, "Task11", false),
        Task(12L, "Task12", false),
        Task(13L, "Task13", true),
        Task(14L, "Task14", false),
        Task(15L, "Task15", false),
    )

    private val _taskList: MutableStateFlow<List<Task>> = MutableStateFlow(list)

    val taskList: StateFlow<List<Task>>
        get() = _taskList.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), listOf())

    fun onCheckedChange(task: Task) {

        val current = _taskList.value
        val replacement =
            current.map { if (it.id == task.id) it.copy(isCompleted = !it.isCompleted) else it }
        _taskList.value = replacement

    }
}

data class Task(val id: Long, var title: String, var isCompleted: Boolean)